package leetCode.secondWeek;

public class Code_59 {
    public int posX = 0;
    public int posY = 0;
    public int directX = 0;
    public int directY = 1;
    public int nCopy;
    int[][] res;

    public int[][] generateMatrix(int n) {
        res = new int[n][n];
        nCopy = n;

        for (int i = 1; i <= Math.pow(n, 2); i++) {
            res[posX][posY] = i;
            next();
        }

        return res;
    }

    public void next() {
        if (posY == nCopy - 1 && posX == 0) {//右上
            directX = 1;
            directY = 0;
            posX += directX;
            posY += directY;
            return;
        }
        if (posX == nCopy - 1 && posY == nCopy - 1) {//右下
            directX = 0;
            directY = -1;
            posX += directX;
            posY += directY;
            return;
        }
        if (posY == 0 && posX == nCopy - 1) {//左下
            directX = -1;
            directY = 0;
            posX += directX;
            posY += directY;
            return;
        }
        if (res[posX + directX][posY + directY] != 0) {//撞到数据了，拐弯
            if (directY == 1) {
                directX = 1;
                directY = 0;
                posX += directX;
                posY += directY;
                return;
            }
            if (directY == -1) {
                directX = -1;
                directY = 0;
                posX += directX;
                posY += directY;
                return;
            }
            if (directX == 1) {
                directX = 0;
                directY = -1;
                posX += directX;
                posY += directY;
                return;
            }
            if (directX == -1) {
                directX = 0;
                directY = 1;
                posX += directX;
                posY += directY;
                return;
            }
        }
        posX += directX;
        posY += directY;
    }
}
